/**
 * 组件中有需要取消发出未相应的请求 mixin
 */
import { Component, Vue } from 'vue-property-decorator'
import axios from 'axios'

const { CancelToken } = axios

@Component({})
export default class CancelRequestMixin extends Vue {
  public cancelTokenSources: { [key: string]: any } = {}

  public createCancelTokenSources(key: string): any {
    if (this.cancelTokenSources[key]) {
      this.cancelTokenSources[key].cancel('cancel request')
    }
    const source: any = CancelToken.source()
    this.cancelTokenSources[key] = source
    return source
  }

  public beforeDestroy() {
    this.cancelAllRequest()
  }

  public cancelAllRequest() {
    Object.values(this.cancelTokenSources).forEach((source: any) => {
      source?.cancel('cancel request')
    })
    this.cancelTokenSources = {}
  }

  public cancelRequestByKey(key: string) {
    this.cancelTokenSources[key].cancel('cancel request')
    delete this.cancelTokenSources[key]
  }
}
